package 开源中国;

import com.alibaba.fastjson.JSON;

import java.util.Arrays;

/**
 * Created by ZhuQianli on 2018/2/7.
 */
public class App {

    public static void main(String[] args) {

        Integer[] items = new Integer[]{null, null, 1, 2, null, null, null, 5, 6, null, null, 55, null, 77, 4, null};

        int nullLeft = -1;
        int nullRight;
        for (int i = 0; i < items.length; i++) {
            Integer item = items[i];
            if (item == null && nullLeft == -1) {
                nullLeft = i;
            } else if (item != null && nullLeft > -1) {
                nullRight = i - 1;
                // 处理数组开头null的情况
                int leftValue = nullLeft - 1 != -1 ? items[nullLeft - 1] : items[nullRight + 1];
                int rightValue = items[nullRight + 1];
                int l = nullLeft;
                int r = nullRight;
                while (l <= r) {
                    items[r--] = rightValue;
                    items[l++] = leftValue;
                }
                nullLeft = -1;
            }
            // 处理数组末尾null的情况
            if (i == items.length - 1 && item == null) {
                int leftValue = items[nullLeft - 1];
                int l = nullLeft;
                while (l < items.length) {
                    items[l++] = leftValue;
                }
            }
        }

        System.out.println(JSON.toJSONString(items));

    }
}
